package com.wzweb.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImageServlet extends HttpServlet {
	public static final String VALIDATE_CODE_SESSION_KEY = "VALIDATE_CODE_SESSION_KEY";

	public ImageServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Pragma","No-cache");    
		response.setHeader("Cache-Control","no-cache");    
		response.setDateHeader("Expires", 0);   
		response.setContentType("image/png");
		String code = createValidateCode();
		request.getSession().setAttribute(VALIDATE_CODE_SESSION_KEY, code);
		Color[] cs = new Color[]{Color.red, Color.blue, Color.YELLOW, Color.GREEN};
		BufferedImage image = new BufferedImage(120, 40, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(Color.gray.brighter());
		g.fillRect(0,0, image.getWidth(), image.getHeight());
		Random r = new Random();
		for (int i = 0; i < 20; i++) {
			g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
			g.drawOval(r.nextInt(image.getWidth())/2, r.nextInt(image.getHeight())/2,r.nextInt(image.getWidth()), r.nextInt(image.getHeight()));
		}

		Font font = new Font("IMPACT", Font.BOLD, 28);
		g.setFont(font);
		for (int i = 0; i < code.length(); i++) {
			int y = r.nextInt(20) + 20;
			g.setColor(Color.black);
			g.drawString("" + code.charAt(i),image.getWidth()/code.length() * i + 3, y + 1);
			g.setColor(cs[i]);
			g.drawString("" + code.charAt(i),image.getWidth()/code.length() * i + 2, y);
		}

		ImageIO.write(image, "PNG", response.getOutputStream());
	}

	private String createValidateCode() {
		String s = "0123456789ABCDEFGHJKMNPQRSTUVWXYZ";
		Random r= new Random();
		return ""+s.charAt(r.nextInt(s.length())) + s.charAt(r.nextInt(s.length())) + s.charAt(r.nextInt(s.length())) + s.charAt(r.nextInt(s.length()));
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
